<template>
  <div
    style="width:100%;"
    @paste="handlePaste"
    v-loading="uploading"
  >
    <el-upload
      drag
      :action="uploadPicUrl"
      :headers="uploadHeaders"
      accept="image/*"
      :before-upload="handleBeforeUpload"
      :on-preview="() => { showViewer = true }"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :file-list="fileList"
      :class="{ limit_height: !!height }"
      :on-remove="handleRemove"
      v-show="!readOnly"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        点击 / 拖拽 / Ctrl+V上传图片
      </div>
      <template #tip>
        <div class="el-upload__tip flex justify-between align-center cursor-pointer">
          图片文件大小不超过{{ limit || 2 }}M
          <span>点击此处后，Ctrl+V上传</span>
        </div>
        <div>

        </div>
      </template>
    </el-upload>
    <div class="demo-image__preview">
      <el-image-viewer
        @close="() => { showViewer = false }"
        v-if="showViewer"
        :url-list="[currentPicUrl]"
      />
    </div>
  </div>
</template>

<script setup>
import request from '@/util/request.ts';
import {getCurrentInstance, ref} from 'vue';
import {generateToken} from '@/util/index.ts';
import { computed } from 'vue';
const { proxy } = getCurrentInstance();

const uploadPicUrl = '/production/files/upload';
const uploadHeaders = {
  Authorization: generateToken(),
};

const props = defineProps(['url', 'list', 'text', 'limit', 'height', 'readonly'])

const readOnly = computed(() => props.readonly);
const showViewer = ref(false);

const currentPicUrl = defineModel('url');
const fileList = defineModel('list');
const uploading = ref(false);

const handleBeforeUpload = file => {
  uploading.value = true;
  const isLt3M = file.size / 1024 / 1024 < (props.limit || 2);
  if (!isLt3M) {
    uploading.value = false;
    proxy.$message.warning(`文件大小超过${props.limit || 2}M限制`);
    return false;
  }
  return true;
};

const handleUploadSuccess = (res, file, fsl) => {
  uploading.value = false;
  if (res.success) {
    currentPicUrl.value = res.data;
    fileList.value = [fsl[fsl.length - 1]];
  } else {
    uploading.value = false;
    proxy.$message.warning('上传失败');
  }
};
const handleUploadError = (error, uploadFile, uploadFiles) => {
  uploading.value = false;
  console.log(error);
  proxy.$message.error(error.toString());
}

const handleRemove = () => {
  currentPicUrl.value = '';
}

const handlePaste = event => {
  uploading.value = true;
  const items = event.clipboardData?.items;
  console.log('items', items);
  if (!items || !items.length) {
    uploading.value = false;
    proxy.$message.warning('无效粘贴内容');
    return;
  };

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    if (item.kind === 'file' && item.type.startsWith('image/')) {
      const file = item.getAsFile();
      if (file) {
        const form = new FormData();
        form.append('file', file);
        request.post('/production/files/upload', form).then(res => {
          uploading.value = false;
          console.log('res', res);
          let { data, success } = res;
          if (success) {
            currentPicUrl.value = data;
            fileList.value = [{ name: props.text || '文件' }];
          } else {
            proxy.$message.warning('上传失败');
          }
        }).then(() => {
          uploading.value = false;
        }).catch(error => {
          uploading.value = false;
        });
      } else {
        uploading.value = false;
        proxy.$message.warning('粘贴内容非图片');
      }
    }
  }
  uploading.value = false;
};


const clearFiles = () => {
  fileList.value = [];
  currentPicUrl.value = '';
};
const preview = () => {
  showViewer.value = true;
}

defineExpose({ clearFiles, preview });
</script>

<style scoped lang="scss">
:deep(.limit_height .el-upload) {
  --el-upload-dragger-padding-horizontal: 5px;

  .el-upload-dragger .el-icon--upload {
    margin-bottom: 0;
  }

  .el-upload__text {
    font-size: 13px;
    line-height: 20px;
    margin-top: -5px;
  }
}

.el-upload__tip {
  margin-top: 0;
  line-height: 22px;
}
</style>